#include <iostream>

using namespace std;

const int N = 1e4 + 10, M = 1010;
typedef long long LL;
LL f[N][M];
LL v[N], w[N], cnt[N];
string be, en;
int n, m;

int main()
{
	char ch;
	int t1, t2, t3, t4;
	cin >> t1 >> ch >> t2 >> t3 >> ch >> t4 >> n;
	int m = t3 * 60 + t4 - (t1 * 60 + t2);
	for(int i = 1; i <= n; i++)
	{
		cin >> v[i] >> w[i] >> cnt[i];
	}
	for(int i = 1; i <= n; i++)
	{
		for(int j = 0; j <= m; j++)
		{
			f[i][j] = f[i - 1][j];
			if(cnt[i] == 0 && j >= v[i]) f[i][j] = max(f[i][j], f[i][j - v[i]] + w[i]);
			else if(cnt[i] == 1 && j >= v[i]) f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i]);
			else 
			{
				for(int k = 1; k <= cnt[i]; k++)
				{
					if(j >= v[i] * k) f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i]);
				}
			}
		}
	}
	cout << f[n][m] << endl;
	return 0;
}
